/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useCallback, forwardRef, useEffect, useState } from "react";
import { Select, Spin } from "antd";
import { connect } from "dva";
import brands from "@kb/brands";

const { Option } = Select;
const initList = [
  {
    brand_en: "all",
    brand: "全部品牌",
  },
];

const Brands = forwardRef((props, ref) => {
  const {
    loading,
    brandList = [],
    dispatch,
    value,
    onSelect,
    requestType,
    mode,
    ...restProps
  } = props;
  const [list, setList] = useState(initList);

  const isKopBrandList = !!requestType;

  const filterOption = useCallback(
    (input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0,
    []
  );

  useEffect(() => {
    setList(prevList => [...prevList, ...brandList]);
  }, []);

  const onDropdownVisibleChange = visible => {
    visible &&
      dispatch({
        type: isKopBrandList ? requestType : "global/getBrandList",
      }).then(res => {
        if (isKopBrandList) {
          const formatBrand =
            res
              ?.map(item => brands.find(itemm => itemm.code === item.brand))
              .map(({ code, name }) => ({
                brand: name,
                brand_en: code,
              })) || [];
          const isNeeddefaultList = mode === "multiple" ? [] : initList;
          setList([...isNeeddefaultList, ...formatBrand]);
          return;
        }
        setList([...initList, ...res]);
      });
  };

  const handleSelect = useCallback(
    (values, options) => {
      onSelect && onSelect(values, options);
    },
    [onSelect]
  );

  return (
    <Select
      onDropdownVisibleChange={onDropdownVisibleChange}
      ref={ref}
      style={{ width: 250 }}
      placeholder="请选择品牌"
      showSearch
      filterOption={filterOption}
      value={value || (mode === "multiple" ? void 0 : "all")}
      onSelect={handleSelect}
      mode={mode}
      {...restProps}
    >
      {loading ? (
        <Option disabled value="loading">
          <Spin />
        </Option>
      ) : (
        list.map(({ brand_en, brand }) => (
          <Option key={brand_en} value={brand_en} name={brand}>
            {brand}
          </Option>
        ))
      )}
    </Select>
  );
});

export default connect(
  ({ loading, global }) => ({
    brandList: global.brandList,
    loading: loading.effects["global/getBrandList"],
  }),
  null,
  null,
  { forwardRef: true }
)(React.memo(Brands));
